package peer.assist.message;

import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.UnknownHostException;

import peer.Message;
import peer.tools.ByteIntSwitch;
import peer.tools.ByteShortSwitch;



public class RegMessage extends Message{
	public short sType=peer.tools.MessageType.sType_Assist_RegMessage;
	InetAddress outIp;
	int outPort;
	byte[] dpData=new byte[12];
	InetAddress lanIp;
	int lanPort;
	public RegMessage(InetAddress outIp,int outPort,InetAddress lanIp,int lanPort){
		byte[] dpData=new byte[20];
		ByteShortSwitch.toByteArray(ver, dpData, 0);  //add: ver
		ByteShortSwitch.toByteArray(sType, dpData, 2);  //add: service type
		System.arraycopy(outIp.getAddress(), 0, dpData, 4, 4);
		ByteIntSwitch.toByteArray(outPort, dpData, 8);
		
		System.arraycopy(lanIp.getAddress(), 0, dpData, 12, 4);
		ByteIntSwitch.toByteArray(lanPort, dpData, 16);
		dp=new DatagramPacket(dpData,dpData.length);
	}
	
	public RegMessage(DatagramPacket dp){
		this.dp=dp;
		dpData=dp.getData();
		ver=ByteShortSwitch.toShort(dpData, 0);
		sType=ByteShortSwitch.toShort(dpData, 2);
		byte[] b=new byte[4];
		System.arraycopy(dpData, 4, b, 0, 4);
		try {
			outIp=InetAddress.getByAddress(b);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		outPort=ByteIntSwitch.toInt(dpData, 8);
		
		byte[] b2=new byte[4];
		System.arraycopy(dpData, 12, b2, 0, 4);
		try {
			lanIp=InetAddress.getByAddress(b2);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		lanPort=ByteIntSwitch.toInt(dpData, 16);
	}
	
	public InetAddress getOutIp(){
		return outIp;
	}
	
	public int getOutPort(){
		return outPort;
	}
	
	public InetAddress getLanIp(){
		return lanIp;
	}
	
	public int getLanPort(){
		return lanPort;
	}
	
	
	
}
